package org.lixue.game.server.handler.socket;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SocketMessageHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) {
        log.debug("channelAdded");
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) {
        log.debug("channelRegistered");
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        log.debug("channelActive");
        // onConnect 连接上
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) {
        log.debug("channelRemoved");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        log.debug("channelRead:" + msg);
        ctx.writeAndFlush("hello client");
        // onMessage 分发消息处理
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        super.userEventTriggered(ctx, evt);
        log.debug("userEventTriggered:{}", evt);
        if(evt instanceof IdleStateEvent){
            log.debug("client idle, disconnect");
            ctx.close();
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.error("exceptionCaught:{}", cause.getMessage());
        ctx.close();
    }
}
